<?php

class User_model extends CI_Model
{
	function CheckIfUserExists($username,$password)
	{	
		$this->load->helper('security');
		$hashPassword=do_hash($password);
		
		$sqlCommand='SELECT ID, prisklassId FROM kund WHERE username = ? AND password = ? AND aktiv =1';
		$result=$this->db->query($sqlCommand,array($username,$hashPassword));
		
		if ($result->num_rows()==1)
		{	
			return $result->row_object(0);
		}
		else
		{
			return FALSE;
		}		
	}
	
	function CheckIfEmailExists($email)
	{
		$sqlCommand='select id,username from kund where email =?';
		$result =$this->db->query($sqlCommand,array($email));
		
		if($result->num_rows()==1)
		{
			//Kod att kör om det finns en användare med email adressen.
			return $result->row(0);
		}
		else
		{
			//Kod att köra om det inte finns en användare med email adressen. 
			return FALSE;
		}
	}
	
	function UpdatePassword($password,$userId)
	{
		$sqlCommand='update kund set password=? where ID =?';
		$result=$this->db->query($sqlCommand,array($password,$userId));
		
		if ($result) //kontrollerar om uppdateringen genomfördes.
		{
			return TRUE;
			
		}
		else
		{
			return FALSE;
		}
	}
	
	function RegisterUser($username,$password,$firstName,$lastName,$personNumber,$adress,$telNumber,$email,$confirmCode)
	{	
	
		$this->load->helper('security');
		$hashPassword=do_hash($password);
		 
		//	$sqlCommand='INSERT INTO kund VALUES (?, ?, ?, ?, ?, ?, ?, ?)';
	
		
		$sqlCommand='INSERT INTO kund (`username`, `password`, `Fnamn`, `Enamn`, `Personnummer`, `Adress`, `TelNummer`, `Email`, `PrisklassID`, `confirmcode`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)';
		
		$result=$this->db->query($sqlCommand,array($username,$hashPassword,$firstName,$lastName,$personNumber,$adress,$telNumber,$email, 1, $confirmCode));
		
		if ($result ==1)
		{	
			return $result;
		}
		else
		{
			return FALSE;
		}
	
	}
	
	function CheckUsername($username)
	{
		$sqlCommand='select id FROM kund WHERE username = ?';
		
		$query=$this->db->query($sqlCommand,array($username));
		
		
		if ($query->num_rows() == 0)
		{
			return TRUE;
		}
		
		else
		{
			
			return FALSE;
		}
	}
	
	function ActivateUser($confirmCode)
	{
	
		$data = array('aktiv' => 1);

		$where = "confirmcode=" . "'" . $confirmCode . "'";

		$str = $this->db->update_string('kund', $data, $where); 
		
		$query=$this->db->query($str);
		
		return $query;
	}	

}